package com.example.player.controller.handler;

import com.example.player.ex.ServiceException;
import com.example.player.web.JsonResult;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * Spring MVC 框架的统一处理异常代码
 * 后续当编写代码时，无论在任何位置，都可以将异常直接抛出，并在此类补充要处理的异常类型,
 * 由统一处理异常的代码进行处理即可！
 *
 * @author fendou2021
 * @create 2022-04-16 10:57
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义的异常ServiceException
     *
     * @param
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleServiceException(ServiceException e) {
        return JsonResult.fail(e);
    }

    /**
     * 处理Spring Boot Validation抛出的异常
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handleBindingException(BindException e){
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return JsonResult.fail(JsonResult.State.BAD_REQUEST, message);
    }
    /**
     * 处理未知异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public JsonResult<Void> handleThrowable(Throwable e) {
        return JsonResult.fail(JsonResult.State.SERVER_ERROR, e.getMessage());
    }

}
